import { defineStore } from 'pinia'
import { ref } from 'vue'
import auth from '@/api/modules/auth'
import system from '@/api/modules/system'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { store } from '@/store'

export const useUserStore = defineStore('user', () => {
  const token = ref(sessionStorage.getItem('accessToken'))
  const isLogining = ref(false) // 登录按钮是否可以点击
  const userInfo = ref({})
  const routes = ref([])
  const roles = ref([])
  const configKey = ref({})
  const unAuthMenu = ref([]) // 用户未授权菜单集合 → 判断路由权限
  const perms = ref([]) // 用户角色编码集合 → 判断路由权限
  // 登录
  function login(tokens) {
    token.value = tokens
    sessionStorage.setItem('accessToken', tokens)
  }
  // 退出登录
  function logout() {
    const tagsViewStore = useTagsViewStore()
    tagsViewStore.delAllViews()
    resetToken()
  }

  // 获取信息(用户基本信息、角色集合、权限集合)
  function getInfo() {
    return new Promise((resolve, reject) => {
      auth
        .loginInfo()
        .then(async ({ data }) => {
          if (!data) {
            return reject('Verification failed, please Login again.')
          }
          userInfo.value = data.user
          routes.value = data.routes
          roles.value = data.roles
          perms.value = data.permissions
          resolve({ ...data })
        })
        .catch((error) => {
          // 移除 token 并跳转登录页
          isLogining.value = false
          reject(error)
        })
    })
  }
  // 获取信息(用户基本信息、角色集合、权限集合)
  function getConfigKey() {
    // 获取首页系统名称和logo
    return new Promise((resolve, reject) => {
      if (!Object.keys(configKey.value).length) {
        system
          .getConfigKey({ configKeys: 'sys.index.slogan,sys.index.logo,sys.index.title,sys.index.copyright' })
          .then((res) => {
            configKey.value.name = res.data['sys.index.title']
            configKey.value.logo = res.data['sys.index.logo']
            configKey.value.slogan = res.data['sys.index.slogan']
            configKey.value.copyright = res.data['sys.index.copyright']
            document.getElementById('labelTitle').innerHTML = configKey.value.name

            resolve(configKey)
          })
          .catch((error) => {
            // 移除 token 并跳转登录页
            reject(error)
          })
      } else {
        resolve(configKey)
        isLogining.value = false
      }
    })
  }

  // 重置
  function resetToken() {
    sessionStorage.setItem('accessToken', '')
    token.value = ''
    userInfo.value = {}
    routes.value = []
    roles.value = []
    perms.value = []
    unAuthMenu.value = []
  }

  // 按钮权限
  function btnJurisdiction(val) {
    if (!val) {
      return true
    }
    if (!perms.value.length) {
      return false
    }
    if (val !== '' && val !== undefined) {
      if (perms.value === undefined) {
        return false
      } else {
        return perms.value[0] === '*:*:*' || perms.value.indexOf(val) !== -1
      }
    }
  }
  /**
   * 获取登录用户未授权菜单
   *
   * @param unAuthMenu 未授权菜单集合
   * @returns
   */
  function getUnAuthMenu() {
    return new Promise((resolve, reject) => {
      system
        .getUnAuthMenu()
        .then((res) => {
          unAuthMenu.value = res.data
          resolve(res.data)
        })
        .catch((error) => {
          isLogining.value = false
          reject(error)
        })
    })
  }
  const setIsLogining = (val) => {
    isLogining.value = val
  }
  return {
    token,
    userInfo,
    routes,
    roles,
    perms,
    isLogining,
    unAuthMenu,
    login,
    logout,
    getInfo,
    getUnAuthMenu,
    getConfigKey,
    resetToken,
    btnJurisdiction,
    setIsLogining,
  }
})

// 非setup
export function useUserStoreHook() {
  return useUserStore(store)
}
